package com.e.dianshang.controller;

import com.e.dianshang.service.SaleService;
import com.e.dianshang.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈静
 * @date 2020/11/11 19:05
 */
@RestController
@Api(value = "秒杀控制器",tags = "秒杀接口的api")
public class SaleController {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    SaleService saleService;

    @PostMapping("/secondSell")
    @ApiOperation(value = "秒杀接口",notes = "秒杀",httpMethod = "POST",response = String.class)
    public Map secondSell(@RequestBody @ApiParam(name = "map",value = "商品信息，对应库存",required = true) Map map) {
//        @RequestParam("phone") String openId,@RequestParam("stock") String stock
       String openId = map.get("phone").toString();
       String stock = map.get("stock").toString();

        JsonResult jsonResult = new JsonResult();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Boolean lock = valueOperations.setIfAbsent("lock", openId,10,TimeUnit.SECONDS);
//        redisTemplate.expire("lock",10, TimeUnit.SECONDS);
        if (lock) {
            Integer stocks = (Integer) valueOperations.get(stock);
            if (stocks > 0) {

                valueOperations.set(stock, --stocks);
                saleService.insertPay(map);
                jsonResult.put("stock",(Integer) valueOperations.get(stock));
                jsonResult.setData("200");
                jsonResult.setMsg("success");

                if(openId.equals(valueOperations.get("lock"))) {
                    redisTemplate.delete("lock");
                }
            }else {
                jsonResult.setCode("400");
                jsonResult.setMsg("库存没有了！");
            }
        }
        return jsonResult.getValues();

    }
}
